/**
 * 
 * 广州锐鹏计算机科技有限公司（www.ruipengkj.com）
 * 
 * 
 * Copyright (c) 2011-2012 RUIPENGKJ.Co.Ltd. All rights reserved.
 * 
 * */
package com.ruipengkj.view.orderView.desk;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.UIManager;

import com.ruipengkj.ApplicationContext;
import com.ruipengkj.bean.TBillDetail;
import com.ruipengkj.bean.TCommodity;
import com.ruipengkj.bean.TConfig;
import com.ruipengkj.bean.TExePos;
import com.ruipengkj.bean.TOrder;
import com.ruipengkj.bean.TStock;
import com.ruipengkj.bean.TStockInOut;
import com.ruipengkj.bean.TStockInOutDetail;
import com.ruipengkj.bean.TStore;
import com.ruipengkj.bean.TUser;
import com.ruipengkj.commons.BuildSpringApplication;
import com.ruipengkj.commons.util.UUID;
import com.ruipengkj.commons.util.Util;
import com.ruipengkj.commons.util.display.ClientDisplay;
import com.ruipengkj.component.JComboBoxPOJO;
import com.ruipengkj.service.TBillDetailService;
import com.ruipengkj.service.TConfigService;
import com.ruipengkj.service.TOrderService;
import com.ruipengkj.service.TStockInOutDetailService;
import com.ruipengkj.service.TStockInOutService;
import com.ruipengkj.service.TStockService;
import com.ruipengkj.service.TStoreService;
import com.ruipengkj.view.base.BasePanel;
import com.ruipengkj.view.orderView.MemberConsumptionConfirmPaymentDailog;
import com.ruipengkj.view.orderView.dish.OrderAddPanel;
import com.ruipengkj.view.orderView.dish.OrderTablePanel;
/**
 * 说明：
 * 餐桌主面板
 */
public class DeskMianPanel extends BasePanel{

	private static final long serialVersionUID = 1L;

	private DeskTypePanel typePanel;// 菜品类型 面板
	private DeskPanel deskPanel;// 餐桌面板
	private JPanel mainPanel;// 菜品类型、菜品、翻页组建 面板
	
	private OrderTablePanel OrderTablePanel;//订单详细
	
	private DeskBottomPanel deskBottomPanel;//桌子底部
	
	private TUser tUser = null;// 会员
	// 配置信息
		private TConfigService tConfigService = BuildSpringApplication
				.getInstance().getTConfigServiceImpl();
//		private TUserService tUserService = BuildSpringApplication.getInstance()
//				.getTUserServiceImpl();// 会员
		private TBillDetailService tBillDetailService = BuildSpringApplication
				.getInstance().getTBillDetailServiceImpl();// 单据商品明细
		private TStockService tStockService = BuildSpringApplication.getInstance()
				.getTStockServiceImpl();// 商品库存
		private TStockInOutService tStockInOutService = BuildSpringApplication
				.getInstance().getTStockInOutServiceImpl();// 出入库单
		private TStockInOutDetailService tStockInOutDetailService = BuildSpringApplication
				.getInstance().getTStockInOutDetailServiceImpl();// 出入库单详细
		private TStoreService tStoreService = BuildSpringApplication.getInstance()
				.getTStoreServiceImpl();// 仓库
		private TOrderService tOrderService = BuildSpringApplication.getInstance().getTOrderServiceImpl();
		
	public DeskMianPanel() {
		init();
	}
	
	private void init() {
		typePanel = new DeskTypePanel() {
			private static final long serialVersionUID = 1L;
			@Override
			// 查询菜品
			public void QueryDesk(String CatalogId) {
				deskPanel.byTypeQueryDesk(CatalogId);
			}
			
			@Override
			protected void setNoDesk() {
				TExePos TExePos = new TExePos();
				TExePos.setName("没有餐桌");
				
				addDesk(TExePos);
				getTExePosCatalog(TExePos);
			}
		};

		deskPanel = new DeskPanel() {
			private static final long serialVersionUID = 1L;

			@Override
			public void AddDesk(TExePos TExePos) {
				addDesk(TExePos);
				getTExePosCatalog(TExePos);
			}
			
		};

		deskPanel.setButtonGroup(typePanel.getNoDeskButton());
		
		deskBottomPanel = new DeskBottomPanel();
		deskBottomPanel.setDeskMianPanel(this);
		
		mainPanel = new JPanel(new BorderLayout()) {
			private static final long serialVersionUID = 1L;

			@Override
			protected void paintComponent(Graphics g) {
				super.paintComponent(g);
				g.setColor(new Color(234, 99, 0));
				g.drawRect(0, 0, this.getWidth() - 1, this.getHeight() - 1);
			}
		};
		
		mainPanel.setOpaque(false);
		deskPanel.setOpaque(false);
		typePanel.setOpaque(false);
		mainPanel.add(typePanel, BorderLayout.NORTH);
		mainPanel.add(deskPanel, BorderLayout.CENTER);

		this.setBackground(new Color(247, 252, 255));
		this.setLayout(new BorderLayout());

		initOrderTablePanel();
		
		this.add(OrderTablePanel, BorderLayout.EAST);
		this.add(mainPanel);
		this.add(deskBottomPanel, BorderLayout.SOUTH);
	} 
	
	private JComboBox desk;
	private void initOrderTablePanel() {
		OrderTablePanel = new OrderTablePanel(1) {

			private static final long serialVersionUID = 1L;
			// 统计总价格----
			@Override
			protected void TotalPrice(int number, int andOrSub) {
				deskBottomPanel.totalPrice(OrderTablePanel.getTCommodityList().get(number), andOrSub);
			}
			// 统计总价格----当跳转到其他订单时
			protected void TotalPrice(TCommodity tCommodity, int num) {
				deskBottomPanel.totalPrice(tCommodity, num);
			}
			//
			public void clear() {
				if (deskBottomPanel != null)
					deskBottomPanel.clear();
			}
		};
		JComboBox desk = OrderTablePanel.getDesk();
		this.desk = desk;
	}
	
	private void getTExePosCatalog(TExePos tExePos){
		if(desk!=null){
			desk.removeAllItems();
			desk.addItem(new JComboBoxPOJO(tExePos.getPosID(),tExePos.getName(), tExePos));
			desk.setSelectedIndex(0);
		}
	}
	
	public void addDesk(TExePos tExePos) {
		OrderTablePanel.queryOrder(tExePos);
	}
	
	/**结账  参数1：应付价格  参数2：折扣  String 下单类型（1结账2下单）*/
	public void BillAction(String should, String discount, int type) {
		if (OrderTablePanel.getTCommodityList().size() <= 0) {
			Util.showMessageDialog("尚未点菜，无需结账/下单！");
			return;
		}
		TOrder tOrder = OrderTablePanel.getOrder();
		String posID = OrderTablePanel.getPosID();
		// 是否有设置仓库
		List<TConfig> tConfigList = null;
		TStore tStore = null;
		try {
			tConfigList = tConfigService.findService(null);
			if (tConfigList == null || tConfigList.size() == 0
					|| tConfigList.get(0).getSellStoreID() == null
					|| tConfigList.get(0).getSellStoreID().equals("")) {
				List<TStore> tStoreList = tStoreService.findService(null);
				if (tStoreList == null || tStoreList.size() == 0) {
					// 没有设置销售仓库，且没有仓库时
					Util.showMessageDialog("请先添加仓库！");
					return;
				} else {
					// 没有设置销售仓库，但有仓库时，默认销售第一个仓库
					tStore = tStoreList.get(0);
				}
			} else {// 有设置销售仓库时
				tStore = new TStore(tConfigList.get(0).getSellStoreID());
			}
		} catch (Exception e2) {
			e2.printStackTrace();
		}

		boolean isSuccess = true;
		if (tOrder == null || tOrder.getOrderID() == null) {
			//订单是新订单时
			tOrder = new TOrder(UUID.GenUUID15());
		} else {
			//订单不是新订单时,删除旧订单项
			try {
				tBillDetailService.deleteService(new TBillDetail(ApplicationContext.BILL_BILLTYPE3, tOrder.getOrderID()));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (type != 2) {
			MemberConsumptionConfirmPaymentDailog dialog = new MemberConsumptionConfirmPaymentDailog(
					null, "支付", true);
			dialog.showDialog(tUser, Double.parseDouble(should),
					tOrder, discount);
			tOrder = dialog.gettOrder();
			isSuccess = dialog.isSuccess;
		} else {
			getTOrder(tOrder, should, posID);
		}
		
		if (isSuccess) {
			try {
				tOrderService.saveOrUpdateService(tOrder);
				List<TCommodity> list = OrderTablePanel.getTCommodityList();
				for (int i = 0; i < list.size(); i++) {
					TCommodity tCommodity = list.get(i);
					
					if (type != 2) {//当现在是下单时，不减库存
						TStock tStock = new TStock();// 根据商品、仓库查出库存
						tStock.setTStore(tStore);
						tStock.setTCommodity(tCommodity);
						List<TStock> tStockList = tStockService
								.findService(tStock);
						if (tStockList != null && tStockList.size() != 0) {
							// 当存在此库存时，修改库存数量
							tStock = tStockList.get(0);
						} else {
							tStock.setStockID(UUID.GenUUID15());
						}
						int num = tCommodity.getNum();// 此商品销售的数量
						tStock.setNum(tStock.getNum() - num);
						tStockService.saveOrUpdateService(tStock);
	
						TStockInOutDetail tStockInOutDetial = new TStockInOutDetail();// 添加出入库单明细
	
						TStockInOut tStockInOut = new TStockInOut();// 添加出入单号
						tStockInOut.setInOutID(UUID.GenUUID15());// 入/出库单编号CHAR(15)PK
						tStockInOut.setType(ApplicationContext.STOCK_TYPE_OUT);// 入/出类型TINYINT
						// 1为入库单
						// 2为出库单
						tStockInOut
								.setSourceType(ApplicationContext.STOCK_IN_OUT_SOURCE_TYPE3);// 1为采购所引起的入库，原因单为采购单编号
						// 2为采购退货所引起的出库，原因单为退货单
						// 3为销售定单所引起的出库，原因单为销售定单 4为销售退货所引起的入库，原因单为销售退货单
						// 5为员工领用所引起的出库，原因单为领用单 6为报损所引起的出库，原因单为报损单
						// 7为仓库调度所引起的出库，原因单为仓库调拨单 8为仓库调度所引起的入库，原因单为仓库调拨单
						// 9为生产材料领用出库 10为生产成品入库 100为未知原因的入库 101为未知原因的出库
						tStockInOut.setSource(tOrder.getOrderID());// 原因单据编号CHAR(15)
						tStockInOut.setOperator(ApplicationContext.OPERATOR_ID);// 操作人
						tStockInOut.setHappenTime(new Date());// 操作时间DATETIME
						tStockInOut.setTStore(tStore);// 仓库
						tStockInOutService.saveService(tStockInOut);// 添加进数据库
						tStockInOutDetial.setTStockInOut(tStockInOut);// 入/出库单
						tStockInOutDetial.setTCommodity(tCommodity);// 商品
						tStockInOutDetailService.saveService(tStockInOutDetial);// 添加进数据库
					}
					
					TBillDetail tBillDetail1 = new TBillDetail();
					tBillDetail1.setDetailID(UUID.GenUUID15());// 明细编号DECIMAL(20,3)PK
					tBillDetail1
							.setBillType(ApplicationContext.BILL_BILLTYPE3);// 单据类型
					tBillDetail1.setBillID(tOrder.getOrderID());// 单据编号CHAR(15)
					tBillDetail1
							.setCommodityID(tCommodity.getCommodityID());// 商品编号
					tBillDetail1.setNum(tCommodity.getNum());// 商品数量INTEGER
					tBillDetail1.setPrice(tCommodity.getDiscountPrice());// 现价DECIMAL(20,3)
					if (tUser != null
							&& tUser.getTShopMemberLevel() != null) {
						tBillDetail1.setDiscount(tUser
								.getTShopMemberLevel().getDiscount());
						tBillDetail1.setDiscountID(tUser
								.getTShopMemberLevel().getLevelID());// 折扣编号CHAR(15)
					} else {
						tBillDetail1.setDiscount(0);
						tBillDetail1.setDiscountID("");
					}
					tBillDetailService.saveService(tBillDetail1);
				}
				
				if (type != 2) {//当现在是下单时，不计算资金出入
					ApplicationContext.addMondyInOut(
									ApplicationContext.MONEYINOUT_TYPE_IN,
									ApplicationContext.OPERATOR_ID,
									ApplicationContext.MONEYINOUT_SOURCE_TYPE3,
									tOrder.getOrderID());
				}
				
				BuildSpringApplication.getInstance().getTOpLogServiceImpl()
						.addOpLogService("添加销售订单信息");
				
				// JOptionPane.showMessageDialog(null, "下单成功");
				if (tConfigList != null && tConfigList.size() != 0
						&& tConfigList.get(0).getPrintNum() != 0) {
					List<TCommodity> commodityList = new ArrayList<TCommodity>();
					for (int i = 0,length = list.size(); i < length; ++i) {
						commodityList.add(list.get(i));
					}
					for (int i = tConfigList.get(0).getPrintNum()-1; i >= 0; --i) {
						deskBottomPanel.printOrder(commodityList, tOrder, OrderTablePanel.getTExePos());// 打印
					}
				}
				OrderTablePanel.queryOrder(null);
			} catch (Exception e1) {
				e1.printStackTrace();
				JOptionPane.showMessageDialog(null, "下单失败");
				return;
			}
			this.clean();
			typePanel.QueryDesk(typePanel.getSelectTExePosCatalog());
		}
	}
	
	/**1、订单 2、总金额 3、实施场所ID*/
	private TOrder getTOrder(TOrder order, String totalMoney, String PosID){
		order.setPosID(PosID);
		order.setWorkShiftID(ApplicationContext.WORKSHIFT_ID);
		//支付方式
		order.setPayWay((byte)0);//付款方式TINYINT  0为尚未支付 1为店付通支付 2为支付宝支付 3为网银支付 4为货到付款  	7现金消费 8会员卡消费 9 刷卡消费";
		order.setStatus(ApplicationContext.ORDER_STATUS02);//TINYINT定单状态1为开始创建的定单 2为确认定单 3为已确定支付方式 4为定单已分配（确认货源） 5为定单正在执行调度 6为定单已发货 7为定单已完成 该字节的10位为撤消标记 0为没有撤消，1为正在撤消
		order.setPayStatus(ApplicationContext.PLAY_STATUS_NO);//支付状态 1为未支付 2为已支付 
		order.setSendWay(ApplicationContext.ORDER_SENDWAY_MODT1);//配送方式  1为送货上门 2为物流 3店内取货
		order.setEndWay(ApplicationContext.ORDER_ENDWAY_MODT0);//结束方式0为未设置 1为成功完成 2为已合并 3为已取消 4为卖家已取消 5为卖家无法送抵（比如说买家不要了）
		order.setTotalAmount(Double.parseDouble(totalMoney.trim()));//总金额DECIMAL(20,3)
		order.setNeedMoney(order.getTotalAmount());//应支付金额
		order.setPayedAmount(0);//已支付金额
		order.setDiscountAmount(0);//优惠金额
//		if (tUser == null || tUser.getTShopMemberLevel() == null) {
//			order.setDiscountAmount(0);
//		} else {
//			order.setDiscountAmount(Double.parseDouble(totalMoneyTF.getText().getText())*tUser.getTShopMemberLevel().getDiscount());
//		}
		
		order.setPayID("");//支付单编号 CHAR(15)
		order.setOrderType(ApplicationContext.ORDERTYPE1);//定单类型 TINYINT 1为个人定单 21为企业定单（个人支付） 22为企业定单（企业支付） 3为楼宇定餐定单，当类型为3时，群组编号为定单生成时的位置编号
		order.setCommentStatus(ApplicationContext.COMMENNTSTATUS1);//评价状态 十位为1商店是否已评价，0为未评价 个位为1商品是否已评价，0为未评价
		order.setCancelReason("");//取消原因 VARCHAR(256)
		order.setNote("");//定单备注 VARCHAR(512)
		order.setSource(ApplicationContext.ORDER_SOURCE1);//订单来源CHAR(15)
		order.setType(ApplicationContext.ORDER_TYPE1+"");//订单类型CHAR(18)1为零售 2为批发
		order.setSaler(ApplicationContext.OPERATOR_ID);//销售人CHAR(15)
		order.setOperator(ApplicationContext.OPERATOR_ID);//操作人CHAR(15)
		order.setBillType(ApplicationContext.BILLTYPE1);//票据类型TINYINT 1为收据  2为发票
		order.setInvoice("");//发票号VARCHAR(30)
		order.setCardPayedAmount(0);//会员卡支持金额DECIMAL(20,3)
		order.setTUser(tUser);
//		order.setSendInfo(null);//配送地址编号CHAR(15)
		return order;
	}

	/**获取订单*/
	public TOrder getOrder() {
		return OrderTablePanel.getOrder();
	}
	
	/**保存订单*/
	public void saveOrder(TOrder order) {
		try {
			if (order == null) {
				tOrderService.saveOrUpdateService(OrderTablePanel.getOrder());
			} else {
				tOrderService.saveOrUpdateService(order);
			}
			OrderTablePanel.queryOrder(null);
			typePanel.QueryDesk(null);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void clean() {
		// 清除table
		OrderTablePanel.newOrder();

		tUser = null;
		try {// 客显清0
			ClientDisplay.sendDisplay(ClientDisplay.DISPLAY_STATE_PRICE, "0");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void delOrder() {
		OrderTablePanel.delOrder();
		deskPanel.byTypeQueryDesk(null);
	}
	
	public static void main(String[] args) {
		try {
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		} catch (Exception e) {
			e.printStackTrace();
		}
		final JFrame frame = new JFrame();
		frame.setSize(1167, 600);
		frame.setLayout(new BorderLayout());
		frame.add(new JPanel(), BorderLayout.NORTH);
		frame.add(new OrderAddPanel());
		frame.setVisible(true);
		frame.addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {
				frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
			}
		});
	}

	public int getTableRow() {
		return OrderTablePanel.getTCommodityList().size();
	}
	
	@Override
	public void clear() {
		clean();

		if (deskBottomPanel != null)
			deskBottomPanel.initThread();
		
		typePanel.termQuery();
		typePanel.QueryDesk(null);
	}
}
